import { defineStore } from 'pinia';

export const useStore = defineStore('main', {
  state: () => {
    // 从localStorage读取用户信息
    const storedUser = localStorage.getItem('currentUser');
    let currentUser = null;
    if (storedUser) {
      try {
        currentUser = JSON.parse(storedUser);
      } catch (e) {
        console.error('解析用户信息失败:', e);
      }
    }
    
    return {
      apiKey: localStorage.getItem('apiKey') || null,
      currentUser: currentUser, // 从localStorage读取的用户信息
      currentSession: localStorage.getItem('currentSession') || 'default_session',
      sessions: JSON.parse(localStorage.getItem('sessions') || '["default_session"]'),
      sessionNames: JSON.parse(localStorage.getItem('sessionNames') || '{}'), // 会话名称映射 {session_id: session_name}
      messages: {},
      loading: false,
      loadingSession: null, // 记录哪个会话正在loading
      error: null
    };
  },
  
  actions: {
    // 保存API Key和用户信息
    setApiKey(key, userInfo = null) {
      this.apiKey = key;
      this.currentUser = userInfo;
      localStorage.setItem('apiKey', key);
      if (userInfo) {
        localStorage.setItem('currentUser', JSON.stringify(userInfo));
      }
      
      // 切换用户时清空前端状态，确保用户隔离
      this.clearUserData();
    },
    
    // 清除API Key和用户数据（退出登录）
    clearApiKey() {
      this.apiKey = null;
      this.currentUser = null;
      localStorage.removeItem('apiKey');
      localStorage.removeItem('currentUser');
      this.clearUserData();
    },
    
    // 清空用户相关的前端数据
    clearUserData() {
      this.currentSession = 'default_session';
      this.sessions = ['default_session'];
      this.sessionNames = {};
      this.messages = {};
      localStorage.setItem('currentSession', this.currentSession);
      localStorage.setItem('sessions', JSON.stringify(this.sessions));
      localStorage.setItem('sessionNames', JSON.stringify(this.sessionNames));
    },
    
    // 添加新会话
    addSession(sessionId, sessionName = null) {
      if (!this.sessions.includes(sessionId)) {
        this.sessions.push(sessionId);
        localStorage.setItem('sessions', JSON.stringify(this.sessions));
      }
      if (sessionName) {
        this.sessionNames[sessionId] = sessionName;
        localStorage.setItem('sessionNames', JSON.stringify(this.sessionNames));
      }
      this.setCurrentSession(sessionId);
    },
    
    // 更新会话名称
    updateSessionName(sessionId, sessionName) {
      this.sessionNames[sessionId] = sessionName;
      localStorage.setItem('sessionNames', JSON.stringify(this.sessionNames));
    },
    
    // 加载会话列表（从服务器）
    async loadSessions(api) {
      try {
        const response = await api.getSessions();
        if (response.data && response.data.sessions) {
          const sessions = response.data.sessions;
          this.sessions = sessions.map(s => s.session_id);
          this.sessionNames = {};
          sessions.forEach(s => {
            this.sessionNames[s.session_id] = s.session_name;
          });
          localStorage.setItem('sessions', JSON.stringify(this.sessions));
          localStorage.setItem('sessionNames', JSON.stringify(this.sessionNames));
        }
      } catch (error) {
        console.error('加载会话列表失败:', error);
      }
    },
    
    // 设置当前会话
    setCurrentSession(sessionId) {
      this.currentSession = sessionId;
      localStorage.setItem('currentSession', sessionId);
    },
    
    // 删除会话
    removeSession(sessionId) {
      this.sessions = this.sessions.filter(id => id !== sessionId);
      localStorage.setItem('sessions', JSON.stringify(this.sessions));
      
      // 删除会话名称
      if (this.sessionNames[sessionId]) {
        delete this.sessionNames[sessionId];
        localStorage.setItem('sessionNames', JSON.stringify(this.sessionNames));
      }
      
      // 如果删除的是当前会话，切换到默认会话
      if (sessionId === this.currentSession) {
        const newSession = this.sessions.length > 0 ? this.sessions[0] : 'default_session';
        this.setCurrentSession(newSession);
      }
    },
    
    // 保存消息到状态
    addMessage(sessionId, isUser, content, timestamp = null) {
      if (!this.messages[sessionId]) {
        this.messages[sessionId] = [];
      }
      
      const message = {
        id: Date.now(),
        isUser,
        content,
        timestamp: timestamp || new Date()
      };
      
      // 只对AI消息添加版本管理
      if (!isUser) {
        message.versions = [content];
        message.currentVersionIndex = 0;
      }
      
      this.messages[sessionId].push(message);
    },
    
    // 添加新版本
    addVersion(sessionId, messageId, newContent) {
      const messages = this.messages[sessionId];
      if (!messages) return;
      
      const message = messages.find(msg => msg.id === messageId);
      if (!message || !message.versions) return;
      
      message.versions.push(newContent);
      message.currentVersionIndex = message.versions.length - 1;
      message.content = newContent;
    },
    
    // 切换版本
    switchVersion(sessionId, messageId, versionIndex) {
      const messages = this.messages[sessionId];
      if (!messages) return;
      
      const message = messages.find(msg => msg.id === messageId);
      if (!message || !message.versions) return;
      
      if (message.versions[versionIndex]) {
        message.currentVersionIndex = versionIndex;
        message.content = message.versions[versionIndex];
      }
    },
    
    // 从历史记录加载消息
    loadHistory(sessionId, history) {
      // 如果当前会话已有消息，不重复加载历史记录
      if (this.messages[sessionId] && this.messages[sessionId].length > 0) {
        return;
      }
      
      this.messages[sessionId] = [];
      
      if (!history) return;
      
      const lines = history.split('\n');
      let currentMessage = null;
      
      // 不再编造时间戳！只使用真实的时间戳
      
      lines.forEach((line) => {
        // 检查是否是带时间戳的新格式：[2025-10-13 14:05:30] 用户：xxx
        const timestampMatch = line.match(/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (用户：|回复：)(.*)$/);
        
        if (timestampMatch) {
          // 新格式：带真实时间戳
          const [, timestamp, prefix, content] = timestampMatch;
          const realTime = new Date(timestamp);
          
          // 保存前一个消息
          if (currentMessage) {
            this.addMessage(sessionId, currentMessage.isUser, currentMessage.content, currentMessage.timestamp);
          }
          
          // 开始新消息
          currentMessage = {
            isUser: prefix === '用户：',
            content: content.trim(),
            timestamp: realTime
          };
        } else if (line.startsWith('用户：')) {
          // 旧格式：无时间戳，不编造时间！
          if (currentMessage) {
            this.addMessage(sessionId, currentMessage.isUser, currentMessage.content, currentMessage.timestamp);
          }
          currentMessage = {
            isUser: true,
            content: line.replace('用户：', '').trim(),
            timestamp: null  // 旧格式没有时间戳，设为null
          };
        } else if (line.startsWith('回复：')) {
          // 旧格式：无时间戳，不编造时间！
          if (currentMessage) {
            this.addMessage(sessionId, currentMessage.isUser, currentMessage.content, currentMessage.timestamp);
          }
          currentMessage = {
            isUser: false,
            content: line.replace('回复：', '').trim(),
            timestamp: null  // 旧格式没有时间戳，设为null
          };
        } else if (currentMessage && line.trim()) {
          // 这是当前消息的续行内容，追加到当前消息
          currentMessage.content += '\n' + line;
        }
      });
      
      // 保存最后一个消息
      if (currentMessage) {
        this.addMessage(sessionId, currentMessage.isUser, currentMessage.content, currentMessage.timestamp);
      }
    },
    
    // 清空会话消息
    clearSessionMessages(sessionId) {
      this.messages[sessionId] = [];
    },
    
    // 删除指定消息
    deleteMessage(sessionId, messageId) {
      if (this.messages[sessionId]) {
        this.messages[sessionId] = this.messages[sessionId].filter(msg => msg.id !== messageId);
      }
    },
    
    // 设置加载状态
    setLoading(state, sessionId = null) {
      this.loading = state;
      // 记录哪个会话正在loading
      this.loadingSession = state ? sessionId : null;
    },
    
    // 设置错误信息
    setError(message) {
      this.error = message;
      // 3秒后自动清除错误信息
      setTimeout(() => {
        this.error = null;
      }, 3000);
    },
    
    // 重新生成最后一次AI回复（添加新版本）
    regenerateLastMessage(sessionId, newContent) {
      const messages = this.messages[sessionId];
      if (!messages || messages.length === 0) return;
      
      // 找到最后一条AI消息（非用户消息）
      for (let i = messages.length - 1; i >= 0; i--) {
        const message = messages[i];
        if (!message.isUser && message.versions) {
          // 添加新版本
          message.versions.push(newContent);
          message.currentVersionIndex = message.versions.length - 1;
          message.content = newContent;
          return;
        }
      }
    }
  }
});
